#!/bin/bash
 
#-------------------------------------------------------------------------------
# iscrestart.sh
# 
# This shell script is invoked from the Restart Inventory Scout Daemon task
# for the process of, obviously, retstarting the Inventory Scout daemon on the
# HSC console machine.
#
# Usage: iscrestart
#
# Return Codes:
# 0 - Inventory Scout daemon restarted successfully
# 1 - Error restarting daemon
# 2 - Error locating log file
#

#-------------------------------------------------------------------------------
# directory and filename which records the save upgrade data actions.
#-------------------------------------------------------------------------------
LOGDIR=/var/hsc/log
LOG=$LOGDIR/iscrestart.log

LOG_ERROR_LOG=/tmp/iscrestart.log

PROGRAM=/usr/sbin/invscoutd
PROGRAM_SHORT=invscoutd

# Check if the directory for the log file exists.
if [ ! -d $LOGDIR ]; then
	echo "=================================================================" > $LOG_ERROR_LOG
	echo -e "Inventory Scout Daemon restart task log for `date`." >> $LOG_ERROR_LOG
	echo "Inventory Scout Daemon restart task log directory, <$LOGDIR>, does not exist. Program exiting" >> $LOG_ERROR_LOG
	exit 2
fi

# Start log to record the Inventory Scout daemon restart actions.
echo -e "Inventory Scout Daemon restart log for `date`.\n" > $LOG


# first determine if the Inventory Scout daemon code is even running
PID=`ps -ef | grep $PROGRAM_SHORT | grep -v grep | awk '{print $2}'`

if test -n "$PID" ; then
	echo "Inventory Scout Daemon currently executing, PID is $PID.">> $LOG 

	# now kill this process and wait a moment before starting a new one
	kill -9 $PID
	sleep 1
        
	# recheck to see if it actually got killed
	PID=`(ps -ef | grep $PROGRAM_SHORT | grep -v grep | awk '{print $2}')` 
	if test -n "$PID" ; then
		echo "Inventory Scout Daemon could not be killed.">> $LOG
	else
		echo "Inventory Scout Daemon successfully stopped.">> $LOG
	fi

else
#   echo No PID
	echo "Inventory Scout Daemon not currently executing.">> $LOG 
fi

# now attempt to restart the daemon
$PROGRAM &

# give it some time to startup and re-check if it's running
sleep 5

PID=`ps -ef | grep $PROGRAM_SHORT | grep -v grep | awk '{print $2}'`
if test -n "$PID" ; then
	echo "Inventory Scout Daemon restarted successfully, new PID is $PID.">> $LOG
	exit 0
else
	echo "Inventory Scout Daemon could not be restarted.">> $LOG
	exit 1
fi

